import java.util.LinkedList;
import java.util.Scanner;

/**
 * @author: gao
 * @create-date: 2025/3/9 21:47
 */
class ListNode{
    int val;
    ListNode next;

    public ListNode() {
    }

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

public class Solution {
    public ListNode reverseList(ListNode head){
        //链表为空，返回null
        if(head == null){
            return null;
        }

        //只有一个结点，返回本身
        if(head.next == null){
            return head;
        }

        ListNode cur = head.next;
        head.next = null;

        while(cur != null){
            ListNode curNext = cur.next;
            cur.next = head;
            head = cur;
            cur = curNext;
        }
        return head;
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(3);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(4);
        ListNode node4 = new ListNode(5);
        ListNode node5 = new ListNode(1);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        Solution solution = new Solution();
        solution.reverseList(node1);

        ListNode cur = node5;
        while(cur != null){
            System.out.print(cur.val+" ");
            cur = cur.next;
        }
    }
}